from django.contrib.auth.models import Permission, Group
from users.models import User
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers


class PermissionSerializer(serializers.ModelSerializer):
    # {
    #     "id": "权限id",
    #     "name": "权限名称",
    #     "codename": "权限识别名",
    #     "content_type": "权限类型ID"
    # }
    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = ('id', 'name')


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        # fields=('id','name','permission')
        fields = '__all__'


class SimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name')


class UserManagerSerializer(serializers.ModelSerializer):
    # "id": "用户id",
    # "username": "用户名",
    # "email": "邮箱",
    # "mobile": "手机号",
    # "groups": ['用户组id', ...],
    # "user_permissions": ['权限id', ...]

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'mobile', 'groups', 'user_permissions')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'required': False,
                'allow_blank': True

            }
        }
    def create(self, validated_data):
        validated_data['is_staff'] = True

        user = super().create(validated_data)

        password = validated_data['password']
        if not password:
            password = '11111111'

        # 对密码进行加密处理
        user.set_password(password)
        user.save()

        return user

class GroupSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name')



